package com.lyl.activiti.demo.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.identity.User;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lyl.activiti.demo.bean.Leave;
import com.lyl.activiti.demo.bpm.cmd.WithdrawTaskCmd;
import com.lyl.activiti.demo.mapper.CustomMapper;
import com.lyl.activiti.demo.mapper.LeaveMapper;

/**
 * 
 * @author lijj
 * 
 */
@Controller
@RequestMapping("/testprocess")
public class TestProcessController extends BaseController {
	@Autowired
	LeaveMapper leaveMapper;
	@Autowired
	CustomMapper customMapper;
	private static final String TEST_PROCESS_DEFINITION_KEY = "testProcess";

	/**
	 * 流程列表
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("/processList")
	public String processList(Model model) {
		List<ProcessDefinition> list = repositoryService
				.createProcessDefinitionQuery().latestVersion()
				.processDefinitionKey(TEST_PROCESS_DEFINITION_KEY)
				.orderByProcessDefinitionId().asc().list();
		model.addAttribute("processList", list);
		return "/testprocess/processList";
	}

	/**
	 * 启动流程
	 * 
	 * @param leave
	 * @param session
	 * @return
	 */
	@RequestMapping("/startProcess")
	public String startProcess(Leave leave, HttpSession session) {
		String userId = ((User) session.getAttribute("user")).getId();
		leave.setApplyUserId(userId);
		leaveMapper.insert(leave);

		identityService.setAuthenticatedUserId(userId);
		runtimeService.startProcessInstanceByKey(TEST_PROCESS_DEFINITION_KEY,
				String.valueOf(leave.getId()));
		return "redirect:/testprocess/processList";
	}

	/**
	 * 待办任务列表
	 * 
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping("/toDoProcessList")
	public String userToDoProcessList(Model model, HttpSession session) {
		String userId = ((User) session.getAttribute("user")).getId();
		List<Task> tasks = taskService.createTaskQuery()
				.processDefinitionKey(TEST_PROCESS_DEFINITION_KEY)
				.taskAssignee(userId).list();
		List<Task> task1 = taskService.createTaskQuery()
				.processDefinitionKey(TEST_PROCESS_DEFINITION_KEY)
				.taskCandidateUser(userId).list();
		
		tasks.addAll(task1);
		model.addAttribute("tasks", tasks);
		// 根据待办中的processInstanceId获得ProcessInstance ProcessDefinition
		HashMap<String, HistoricProcessInstance> historicProcessInstances = new HashMap<String, HistoricProcessInstance>();
		HashMap<String, ProcessDefinition> processDefinitions = new HashMap<String, ProcessDefinition>();
		for (Task task : tasks) {
			ProcessDefinition processDefinition = repositoryService
					.createProcessDefinitionQuery()
					.processDefinitionId(task.getProcessDefinitionId())
					.singleResult();
			processDefinitions.put(task.getProcessDefinitionId(),
					processDefinition);

			HistoricProcessInstance historicProcessInstance = historyService
					.createHistoricProcessInstanceQuery()
					.processInstanceId(task.getProcessInstanceId())
					.singleResult();
			historicProcessInstances.put(task.getProcessInstanceId(),
					historicProcessInstance);
		}
		model.addAttribute("historicProcessInstances", historicProcessInstances);
		model.addAttribute("processDefinitions", processDefinitions);
		return "/testprocess/toDoProcessList";
	}

	/**
	 * 签收流程
	 * 
	 * @param taskId
	 * @param session
	 * @return
	 */
	@RequestMapping("/claimProcess")
	public String claimProcess(String taskId, HttpSession session) {
		String userId = ((User) session.getAttribute("user")).getId();
		Task task=taskService.createTaskQuery().taskId(taskId).singleResult();
		// 判断任务是否已经被签收
		if(task.getAssignee()==null){
			taskService.claim(taskId, userId);
		}
		return "redirect:/testprocess/toDoProcessList";
	}

	/**
	 * 获取任务表单
	 * 
	 * @param taskDefinitionKey
	 * @param taskId
	 * @param processInstanceId
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getTaskForm/{taskDefinitionKey}/{taskId}/{processInstanceId}")
	public String getTaskForm(
			@PathVariable("taskDefinitionKey") String taskDefinitionKey,
			@PathVariable("taskId") String taskId,
			@PathVariable("processInstanceId") String processInstanceId,
			Model model) throws Exception {
		ProcessInstance processInstance = runtimeService
				.createProcessInstanceQuery()
				.processInstanceId(processInstanceId).singleResult();
		Leave leave = leaveMapper.selectByPrimaryKey(Integer
				.parseInt(processInstance.getBusinessKey()));
		model.addAttribute("leave", leave);
		model.addAttribute("taskId", taskId);
		return "/testprocess/managerApprove";
		/*
		 * if ("managerApprove1".equals(taskDefinitionKey)) { return
		 * "/testprocess/managerApprove"; } else if
		 * ("managerApprove2".equals(taskDefinitionKey)) { return
		 * "/testprocess/managerApprove2"; } else if
		 * ("managerApprove3".equals(taskDefinitionKey)) { return
		 * "/testprocess/managerApprove3"; } return "";
		 */
	}

	/**
	 * 完成经理审批
	 * 
	 * @param leave
	 * @param deptLeaderPass
	 * @param taskId
	 * @param session
	 * @return
	 */
	@RequestMapping("/completeTaskManagerApprove")
	@ResponseBody
	public String completeTaskManagerApprove(Leave leave,
			@RequestParam("deptLeaderPass") String deptLeaderPass,
			@RequestParam("taskId") String taskId, HttpSession session) {
		String userId = ((User) session.getAttribute("user")).getId();
		leaveMapper.updateByPrimaryKeySelective(leave);
		Map<String, String> formProperties = new HashMap<String, String>();
		Object obj = session.getAttribute("count");
		int count = 0;
//		if (deptLeaderPass.equals("true")) {
//			if (obj == null) {
//				count = 1;
//			} else {
//				count = Integer.parseInt(obj.toString()) + 1;
//			}
//			session.setAttribute("count", String.valueOf(count));
//		}

		formProperties.put("count", String.valueOf(count));
		try {
			identityService.setAuthenticatedUserId(userId);
			formService.submitTaskFormData(taskId, formProperties);
		} finally {
			identityService.setAuthenticatedUserId(null);
		}
		return "true";
	}

	/**
	 * 已办任务
	 * 
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping("/processedTaskList")
	public String processedTaskList(Model model, HttpSession session) {
		String userId = ((User) session.getAttribute("user")).getId();
		List<HistoricTaskInstance> processedTasks = historyService
				.createHistoricTaskInstanceQuery().taskAssignee(userId)
				.finished().list();
		model.addAttribute("processedTasks", processedTasks);
		HashMap<String, HistoricProcessInstance> processInstances = new HashMap<String, HistoricProcessInstance>();
		for (HistoricTaskInstance historicTaskInstance : processedTasks) {
			HistoricProcessInstance historicProcessInstance = historyService
					.createHistoricProcessInstanceQuery()
					.processInstanceId(
							historicTaskInstance.getProcessInstanceId())
					.singleResult();
			processInstances.put(historicTaskInstance.getProcessInstanceId(),
					historicProcessInstance);
		}
		model.addAttribute("processInstances", processInstances);
		return "/testprocess/processedTaskList";
	}
	/**
     * 撤销已办任务
     * @param taskId
     * @return
     */
    @RequestMapping(value = "/callBack/{taskId}")
    @ResponseBody
    public String callBack(@PathVariable("taskId") String taskId){
        Command<Integer> cmd = new WithdrawTaskCmd(taskId);
        return managementService.executeCommand(cmd).toString();
    }
}
